import imhere.exceptions.DataFileException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;



public class DataBase {
	
	private final String DATA_FILE = "data.xml";
	
	private static DataBase data = null;
	
	protected DataBase(){
		
	}
	
	public synchronized static DataBase getInstance(){
		if (data == null){
			data = new DataBase();
		}
		return data;
	}
	
	/**
	 * Save DATA in DataBase.
	 * 
	 * @throws DataFileException
	 */
	public void saveData() throws DataFileException {
		XStream xstream = new XStream(new DomDriver());

		xstream.alias("User", User.class);

		String xml = xstream.toXML(UserControl.getInstance().getUsers());

		try {
			File fileAux = new File(DATA_FILE);
			if (fileAux.exists() && fileAux.isFile()) {
				fileAux.delete();
			}

			FileWriter file = new FileWriter(new File(DATA_FILE), true);
			file.write(xml);
			file.close();
		} catch (IOException e) {
			throw new DataFileException(
					"Nao foi possivel salvar os dados no arquivo: " + DATA_FILE);
		}
	}
	
	/**
	 * Load DATA from database.
	 * 
	 * @throws DataFileException
	 *             - if load datas from database occurs any problem, like
	 *             deleted or corrupted file
	 */
	@SuppressWarnings("unchecked")
	public void loadData() throws DataFileException {
		try {
			BufferedReader in = new BufferedReader(new FileReader(DATA_FILE));

			String s;

			StringBuilder sb = new StringBuilder();
			while ((s = in.readLine()) != null) {
				sb.append(s + "\n");
			}
			in.close();
			XStream xstream = new XStream(new DomDriver());
			
			UserControl.getInstance().setUsers((HashMap<String, UserLoggable>) xstream.fromXML(sb
					.toString()));

		} catch (IOException e) {
			throw new DataFileException(
					"Nao foi possivel ler os dados do arquivo: " + DATA_FILE);
		}

	}

}
